﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using eShop.Domain;
using Microsoft.Practices.Unity;

namespace eShop.Application
{
    public class ApplicationServiceFactory
    {
        #region Application Service UnityContainer Singleton
        
        private const string InstanceContextName = "AppServiceContainerInstance";
        
        private static IUnityContainer _appServiceContainerInstance;
        
        private static IUnityContainer AppServiceContainerInstance
        {
            get
            {
                if (HttpContext.Current == null)
                {
                    if (_appServiceContainerInstance == null)
                    {
                        _appServiceContainerInstance = InitializeServiceContainer();
                    }
                    return _appServiceContainerInstance;
                }

                if (!HttpContext.Current.Items.Contains(InstanceContextName))
                {
                    HttpContext.Current.Items.Add(InstanceContextName, InitializeServiceContainer());
                }

                return (IUnityContainer)HttpContext.Current.Items[InstanceContextName];
            }
        }

        private static IUnityContainer InitializeServiceContainer()
        {
            IUnityContainer unityContainer = DomainRepositoryFactory.CreateChildContainer();

            InitializeApplicationServices(unityContainer);
            return unityContainer;
        }

        #endregion

        private static void InitializeApplicationServices(IUnityContainer unitiyContainer)
        {
            //unitiyContainer.RegisterType<ICustomerService, CustomerService>();
        }

        #region Factory static methods

        public static TServiceInterface GenerateImplementation<TServiceInterface>()
        {
            return AppServiceContainerInstance.Resolve<TServiceInterface>();
        }

        public static void TearDown()
        {
            DomainRepositoryFactory.TearDown();
        }

        #endregion
    }
}
